/*
 * Copyright 2022 Institute of Software Chinese Academy of Sciences, ISRC
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import prompt from '@system.prompt';
import router from '@system.router';
import http from '@ohos.net.http';

//群二维码假数据
const qrcode = {
    id: 1,
    imgUrl: 'common/images/personPic/1.png',
    text: '群二维码',
    url: '',
    find_right_icon: '/common/images/findPic/find-right-icon.png'
}

//页面功能假数据
const GtalkList = [
    { id: 1, text: '查找聊天记录', url: '', },
    { id: 2, text: '消息免打扰', url: '', },
    { id: 3, text: '置顶聊天', url: '', },
    { id: 4, text: '提醒', url: '', },
    { id: 5, text: '设置当前聊天背景', url: '', },
    { id: 6, text: '清空聊天记录', url: '', }
];

//群成员假数据
const avatarList = [
    { type:'user', imgUrl:'/common/images/sessionPic/img_1.png', userId:'', title:'小蔡' },
];


export default {
    data: {
        GtalkList: GtalkList,
        //路由使用，对群聊单聊的共用页告知本页为群聊页
        sayOrGroup:'group',
        //群内等级
        groupLevel:0,
        //群基本信息
        avatarList: avatarList,
        groupName:'',
        groupId:'',
        qr:qrcode,
        userGroupNickname: '',
        //群禁言
        isTalkForbidden: false,
        //群私聊所用变量
        addFromGroup:false,
        find_right_icon: '/common/images/findPic/find-right-icon.png',
    },
    onInit() {
        this.groupId=router.getParams().sayOrGroup_ID
        this.sayOrGroup=router.getParams().sayOrGroup
        this.isTalkForbidden=router.getParams().isTalkForbidden
        this.getGroupMembers();
        this.getUserGroupNickname();
    },
    onShow() {
        this.getGroupLevel();
        this.getAddForbiddenStatus();
    },
    backToSession(){
        router.back();
    },
    //获取群内等级，以此针对性展示页面
    getGroupLevel(){
        //接口
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/getUserPrivilege", {
            method:'POST',
            extraData:JSON.stringify({
                "uid":this.$app.$def.uid,
                "groupId":this.groupId
            }),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re  = JSON.parse(value.result.toString())
            console.info('groupChatMessage====>groupPrivilege: '+re.data)
            if(re.code == 200) {
                this.groupLevel = re.data
                if(re.data === 0){
                    prompt.showToast({
                        message: '本账号为群主',
                        duration: 2000,
                    });
                }
                else if(re.data === 1){
                    prompt.showToast({
                        message: '本账号为管理员',
                        duration: 2000,
                    });
                }
                else if(re.data === 2){
                    prompt.showToast({
                        message: '本账号为群成员',
                        duration: 2000,
                    });
                }
            }
        }).catch((err) => {
            prompt.showToast({
                message: '群等级未获取成功，网络',
                duration: 2000,
            });
            console.error(`groupChatMessage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //获取群成员列表
    getGroupMembers() {
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/groupMembersList/" + this.groupId, {
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            this.re  = JSON.parse(value.result.toString())
            let re = this.re;
            console.info('groupChatMessage====>getGroupMembers: '+re)
            if(re.code == 200) {
                this.avatarList = []
                this.$app.$def.groupMembersList = []
                for (let i = 0; i < re.data.length; i++) {
                    let groupMember = {
                        type: 'user',
                        imgUrl: '/common/images/sessionPic/img_' + Math.round(Math.random()*7+1) + '.png',
                        text: re.data[i],
                        userId: re.data[i]
                    }
                    this.avatarList.push(groupMember)
                    this.$app.$def.groupMembersList.push(groupMember)
                }
            }
        }).catch((err) => {
            console.error(`groupChatMessage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //点击用户头像，判断是否为好友，跳转好友/非好友详情页
    intoMemberDetails(idx){
        let groupMemberId = this.avatarList[idx].userId;
        console.info('groupChatMessage====>this.avatarList[idx].userId: ' + groupMemberId)
        //接口判断
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/user/isFriend", {
            method:'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid, "touid":groupMemberId}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            console.info('groupChatMessage====>getGroupMembers: ' + re.toString())
            if (re.msg === '双方不是好友') {
                router.push({
                    uri: "pages/notFriendDetail/notFriendDetail",
                    params: {
                        sayOrGroup: 'say',
                        groupMemberId:groupMemberId,
                        addFromGroup: this.addFromGroup,
                    },
                });
            }
            else if (re.msg === '双方是好友') {
                let friendId=this.getFriendId(groupMemberId);
                console.info("groupChatMessage=====> friendId:" + friendId);
                router.push({
                    uri: "pages/dialogPage/chatMessagePage/friendDetails/friendDetails",
                    params: {
                        sayOrGroup: 'say',
                        groupMemberId: groupMemberId,
                        sourcePage: 'groupChatMessage',
                        sayOrGroup_ID:friendId
                    },
                });
            }
        })
    },
    //遍历通讯录页得出是好友的人是第几个好友
    getFriendId(groupMemberId){
        let friendId=0;
        console.info("groupChatMessage====>getFriendId this.$app.$def.friendsList[0].id:"+this.$app.$def.friendsList[0].id)
        for(let i=0;i<this.$app.$def.friendsList.length;i++){
            if(this.$app.$def.friendsList[i].id.toString()===groupMemberId.toString())
                friendId=i;
        }
        console.info("groupChatMessage====>getFriendId"+friendId)
        return friendId;
    },
    //跳转邀请进群页
    intoAdd(){
        router.push({
            uri: "pages/createGroup/createGroup",
            params: {
                operation: 'invite',
                groupId: this.groupId,
            },
        });
    },
    //跳转踢出群聊页
    intoDelete(){
        router.push({
            uri: "pages/createGroup/createGroup",
            params: {
                operation: 'delete',
                groupId: this.groupId,
            },
        });
    },
    //群二维码
    toQrCode(){
        router.push({
            uri: "pages/myList/qrcode/qr",
            params: {
                sayOrGroup: 'group',
                groupId: this.groupId,
            },
        });
    },
    getUserGroupNickname() {
        let httpRequest = http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/getUserGroupNickname", {
            method: 'POST',
            extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            if(re.code == 200){
                prompt.showToast({
                    message: "获取用户群昵称成功"
                });
                console.info("chatMessagePage=====getUserGroupNickname re.data : " + re.data);
                this.userGroupNickname = re.data;
            } else {
                prompt.showToast({
                    message: "获取用户群昵称失败"
                });
            }
        }).catch((err) => {
            console.error(`chatMessagePage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    clickNickname() {
        router.push({
            uri: "pages/dialogPage/chatMessagePage/changeUserGroupNickname/changeUserGroupNickname",
            params: {
                groupId: this.groupId,
            },
        });
    },
    //群禁言状态切换
    groupForbiddenSwitch(e){
        console.log("groupChatMessage====>groupForbiddenSwitch"+e.checked);
        if(e.checked){
            // 设置群禁言
            //        TODO  未完成
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/forbidTalk", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                if(re.code == 2039){
                    prompt.showToast({
                        message: "禁言群组成功"
                    });
                } else if(re.code == 2040){
                    prompt.showToast({
                        message: "禁言群组失败"
                    });
                }
            }).catch((err) => {
                console.error(`groupChatMessage====>groupForbiddenSwitch:${err.code}, errMessage1:${err.data}`);
            });
        }else{
            // 取消群禁言
            //        TODO  未完成
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/cancelForbid", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid, "groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((value) => {
                let re = JSON.parse(value.result.toString())
                if(re.code == 2043){
                    prompt.showToast({
                        message: "取消群组禁言成功"
                    });
                } else if(re.code == 2040){
                    prompt.showToast({
                        message: "取消群组禁言失败"
                    });
                }
            }).catch((err) => {
                console.error(`groupChatMessage====>groupForbiddenSwitch:${err.code}, errMessage1:${err.data}`);
            });
        }
    },
    //获取群私聊状态
    getAddForbiddenStatus(){
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/isAllowedPrivateChat", {
            method:'POST',
            extraData:JSON.stringify({
                "groupId":this.groupId
            }),
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re  = JSON.parse(value.result.toString())
            console.info('groupChatMessage====>getAddForbiddenStatus: '+JSON.stringify(re))
            if(re.code === 2049) {
                this.addFromGroup = true;
            }
            else if(re.code === 2050) {
                this.addFromGroup = false;
            }
        }).catch((err) => {
            console.error(`groupChatMessage====> errCode:${err.code}, errMessage1:${err.data}`);
        });
    },
    //改变群私聊状态
    changeAddForbiddenStatus(){
        console.info("groupChatMessage====>changeAddForbiddenStatus"+this.addFromGroup)
        if(this.addFromGroup===true){
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/forbidPrivateChat", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid,"groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((res) => {
                let re = JSON.parse(res.result.toString())
                console.info("groupChatMessage====>changeAddForbiddenStatus"+JSON.stringify(re))
                if(re.code == 2051) {
                    this.addFromGroup=false
                    prompt.showToast({
                        message: '该群已禁止私聊',
                        duration: 2000,
                    });
                }
                else if(re.code == 2052) {
                    this.addFromGroup=true
                    prompt.showToast({
                        message: '禁止私聊失败,逻辑',
                        duration: 2000,
                    });
                }
            }).catch(() => {
                prompt.showToast({
                    message: '禁止私聊失败,网络',
                    duration: 2000,
                });
                this.addFromGroup=true
            });
            httpRequest.destroy();
        }
        else if(this.addFromGroup===false){
            let httpRequest= http.createHttp();
            let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/allowPrivateChat", {
                method: 'POST',
                extraData:JSON.stringify({"uid":this.$app.$def.uid,"groupId":this.groupId}),
                connectTimeout: 60000,
                readTimeout: 60000,
                header: {
                    'Content-Type': 'application/json'
                }
            });
            promise.then((res) => {
                let re = JSON.parse(res.result.toString())
                console.info("groupChatMessage====>changeAddForbiddenStatus"+JSON.stringify(re))
                if(re.code == 2053) {
                    this.addFromGroup=true;
                    prompt.showToast({
                        message: '该群已允许私聊',
                        duration: 2000,
                    });
                }
                else if(re.code == 2054) {
                    this.addFromGroup=false;
                    prompt.showToast({
                        message: '允许私聊失败,逻辑',
                        duration: 2000,
                    });
                }
            }).catch(() => {
                this.addFromGroup=false;
                prompt.showToast({
                    message: '允许私聊失败,网络',
                    duration: 2000,
                });
            });
            httpRequest.destroy();
        }
        else{
            console.info('groupChatMessage====>changeAddForbiddenStatus：addFromGroup status undefined')
        }
    },
    //解散群聊
    dismiss() {
        //todo dismiss this.groupId
        console.info('groupChatMessage====>dismiss:' + this.groupId)
        let httpRequest= http.createHttp();
        let promise = httpRequest.request("http://" + this.$app.$def.ip +"/group/disband/" + this.groupId, {
            method: 'POST',
            connectTimeout: 60000,
            readTimeout: 60000,
            header: {
                'Content-Type': 'application/json'
            }
        });
        promise.then((value) => {
            let re = JSON.parse(value.result.toString())
            console.info('groupChatMessage====>dismiss:'+re)
            if(re.code == 2027) {
                prompt.showToast({
                    message: '解散成功',
                    duration: 2000,
                });
                router.push({
                    uri:'pages/sessionList/sessionList'
                })
            } else if(re.code == 2028) {
                prompt.showToast({
                    message: '解散失败',
                    duration: 2000,
                });
            }
        }).catch((err) => {
            console.error(`groupChatMessage====>dismiss:${err.code}, errMessage1:${err.data}`);
        });
    },
}